import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Picker, Text, Block} from "@tarojs/components";
import "./index.scss";
import {user} from "../../utils/user.service";
import {
  CHILD_SELLER_LIST_SUM_DATA,
  DISTRIBUTION_ORDER_SUM_DATA,
  IDENTITY,
  MY_REPORT_DATA,
  TOP_THREE
} from "../../constants/api";
import {http} from "../../utils/http";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth";
import {vcmonitor} from "../../utils/tools";
import {AtIcon} from "taro-ui";
import {newHttp} from "../../utils/request";
import Water from "../components/water-mark/index";

export default class Member extends Component {
  state: {
    userIdentity: any
    infoOne: any
    infoTwo: any
    childData: any
    tipsNum: number
    // Tab 激活状态
    active: number
    // 日报
    day_date: string
    // 月报
    month_date: string

    // 自定义 起始时间
    show: boolean
    start_date: string
    end_date: string

    // 右侧显示的文本
    date_right: string

    // 数据总览
    dataOverViewOne: number
    dataOverViewTwo: number
    dataOverViewThree: number

    // 收益榜TOP3
    listTableData: any
  } = {
    userIdentity: {},
    infoOne: {},
    infoTwo: {},
    childData: {},
    tipsNum: 0,
    // Tab 激活状态
    // 1:日报 2:月报 3:自定义
    active: 1,

    // 日报
    day_date: "",
    // 月报
    month_date: "",

    // 自定义 起始时间
    show: false,
    start_date: "起始时间",
    end_date: "终止时间",

    // 右侧显示的文本
    date_right: "2021/10/01",

    // 数据总览
    dataOverViewOne: 0,
    dataOverViewTwo: 0,
    dataOverViewThree: 0,
    // 收益榜TOP3
    listTableData: []
  };

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {

    if (process.env.TARO_ENV === "h5") {
      await h5Wx.getConfig();
    }

    // 获取当前时间戳 转换为 2021/10/01 格式
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();

    month = +month;
    day = +day;

    month = month >= 10 ? month : "0" + month;
    day = day >= 10 ? day : "0" + day;

    let temp = "";
    temp = year + "/" + month + "/" + day;

    this.setState({date_right: temp});

    // 时间格式转换成-
    temp = this.timeFormatConversion(temp);

    await this.setStateSync({day_date: temp});

    // 设置默认 起始时间
    await this.setState({start_date: temp, end_date: temp});

    // 设置默认 年月
    await this.setState({month_date: temp.slice(0, 7)});

    // 登录
    const isLogin = await user.checkLogin();
    if (!isLogin) {
      Taro.showToast({
        title: "你还未登录，请登录",
        icon: "none"
      });
      const timer = setTimeout(() => {
        clearTimeout(timer);
        Taro.switchTab({url: "/pages/index/index"});
      }, 1500);
      return;
    }

    // 获取 数据总览
    this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
  }

  // 获取 数据总览
  async getDataOverView() {

    // const active = this.state.active;
    // const tempObj = {};
    //
    // if (active == 1) {
    //   tempObj.search_date_start = this.state.day_date;
    //   tempObj.search_date_end = this.state.day_date;
    // } else if (active == 2) {
    //   tempObj.search_month = this.state.month_date;
    // } else if (active == 3) {
    //   tempObj.search_date_start = this.state.start_date;
    //   tempObj.search_date_end = this.state.end_date;
    // }
    //
    // const res = await http.HGet(MY_REPORT_DATA, tempObj);
    // if (res) {
    //   const {estimatedEarnings: e, newTalent: n, orderNum: o} = res.data;
    //   this.setState({
    //     dataOverViewOne: e,
    //     dataOverViewTwo: o,
    //     dataOverViewThree: n
    //   });
    // }
  }

  // 获取 收益榜TOP3
  async getProfitList() {

    const active = this.state.active;
    const tempObj = {};
    const data1 = { search_type: 0 }
    const data2 = { search_type: 1 }
    if (active == 1) {
      tempObj.search_date_start = this.state.day_date;
      tempObj.search_date_end = this.state.day_date;
      data1.search_date_start = this.state.day_date;
      data1.search_date_end = this.state.day_date;
      data2.search_date_start = this.state.day_date;
      data2.search_date_end = this.state.day_date;
    } else if (active == 2) {
      tempObj.search_month = this.state.month_date;
      data1.search_month = this.state.month_date;
      data2.search_month = this.state.month_date;
    } else if (active == 3) {
      tempObj.search_date_start = this.state.start_date;
      tempObj.search_date_end = this.state.end_date;
      data1.search_date_start = this.state.start_date;
      data1.search_date_end = this.state.end_date;
      data2.search_date_start = this.state.start_date;
      data2.search_date_end = this.state.end_date;
    }
    const userIdentity = await http.get(IDENTITY, tempObj);
    const resList = await http.HGet(TOP_THREE, tempObj);
    const res = await http.HGet(CHILD_SELLER_LIST_SUM_DATA, tempObj);
    const infoOne = await newHttp.catchGet(DISTRIBUTION_ORDER_SUM_DATA, data1)
    const infoTwo = await newHttp.catchGet(DISTRIBUTION_ORDER_SUM_DATA, data2)
    this.setState({ childData: res.data, userIdentity, infoOne, infoTwo })
    if (resList) {
      const reportData = resList.data;

      // 重新组装一下要渲染的数据
      const tempArr = [];
      for (let i = 0; i < reportData.length; i++) {
        const tempObj = {};
        tempObj.id = reportData[i].id;
        tempObj.url = reportData[i].img;
        tempObj.title = reportData[i].name;
        tempObj.get = reportData[i].money;
        tempObj.orderNums = reportData[i].cnt;
        if (typeof reportData[i].is_pub !== 'undefined') {
          tempObj.onSale = reportData[i].is_pub == 1 ? true : false;
        } else {
          tempObj.onSale = reportData[i].is_sale == 1 ? true : false;
        }
        tempObj.navigateto = reportData[i].url || "";
        tempArr.push(tempObj);
      }
      this.setState({
        listTableData: tempArr
      });
    }

  }

  // 日报
  async bindDayDateChange(e) {
    await this.setStateSync({active: 1});
    await this.setStateSync({day_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});
    Taro.showLoading({title: '加载中...'})
    // 获取 数据总览
    await this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
    Taro.hideLoading()
  }

  // 月报
  async bindMonthDateChange(e) {

    await this.setStateSync({active: 2});
    await this.setStateSync({month_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});

    Taro.showLoading({title: '加载中...'})
    // 获取 数据总览
    await this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
    Taro.hideLoading()
  }

  // 起
  async bindStartDateChange(e) {

    await this.setStateSync({start_date: e.detail.value});
    this.setState({date_right: "全部"});

    Taro.showLoading({title: '加载中...'})
    // 获取 数据总览
    await this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
    Taro.hideLoading()
  }

  // 止
  async bindEndDateChange(e) {

    await this.setStateSync({end_date: e.detail.value});
    this.setState({date_right: "全部"});

    Taro.showLoading({title: '加载中...'})
    // 获取 数据总览
    await this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
    Taro.hideLoading()
  }

  // 点击 切换 Tabs active
  async activeTabs(num) {
    await this.setStateSync({active: num})

    if (num == 1) {
      let temp = this.state.day_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }

    if (num == 2) {
      let temp = this.state.month_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }

    // 显示 自定义 日期区间选择器
    if (num == 3 && this.state.show == false) {
      this.setState({show: true});
    } else {
      this.setState({show: false});
    }
    Taro.showLoading({title: '加载中...'})
    // 获取 数据总览
    await this.getDataOverView();

    // 获取 收益榜TOP3
    await this.getProfitList();
    Taro.hideLoading()
  }

  // 时间格式转换  /转-
  timeFormatConversion(str) {
    return str.split("/").join("-");
  }

  // 时间格式转换  -转/
  timeFormatConversionElse(str) {
    return str.split("-").join("/");
  }

  // setState 异步转同步
  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  // 跳转
  onNavigateTo(url, onSale) {
    onSale && Taro.navigateTo({url});
  }

  jump(type) {
    const {active, day_date, month_date, end_date, start_date} = this.state
    let url = '/distributor/report/detail/estimatedIncome'
    if (type) {
      url = '/main/order/promotionOrder'
    }
    if (active === 1) {
      url += `?search_date_start=${day_date}&active=${active}`
    } else if (active === 2) {
      url += `?search_month=${month_date}&active=${active}`
    } else if (active === 3) {
      url += `?search_date_start=${start_date}&search_date_end=${end_date}&active=${active}`
    }
    Taro.navigateTo({url})
  }

  showTips(num) {
    this.setState({tipsNum: num})
  }

  jumpOther(url, type){
    const {active, day_date, month_date, end_date, start_date} = this.state
    if (active === 1) {
      url += `?search_date_start=${day_date}&active=${active}`
    } else if (active === 2) {
      url += `?search_month=${month_date}&active=${active}`
    } else if (active === 3) {
      url += `?search_date_start=${start_date}&search_date_end=${end_date}&active=${active}`
    }
    url += `&type=${type || ''}`
    Taro.navigateTo({url})
  }
  jumpOthers(url){
    Taro.navigateTo({url})
  }

  render() {
    const {
      userIdentity,
      active,
      show,
      tipsNum,
      childData,
      start_date,
      end_date,
      date_right,
      infoOne,
      infoTwo,
      listTableData
    } = this.state;

    return (
      <View className='report'>
        <GzhAuth />
        <Water />
        {/* 顶部 日报 月报 自定义 日期选择器 */}
        <View className='select-time'>
          <View className='left flex-row'>
            <View
              className={`mar-right ${active === 1 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 1)}
            >
              <View>日报</View>
            </View>
            <View
              className={`mar-right ${active === 2 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 2)}
            >
              <View>月报</View>
            </View>
            <View
              className={`${active === 3 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 3)}
            >
              <View>自定义</View>
            </View>
          </View>
          {/* 右侧的 picker 组 */}
          <View className='right'>
            {/* 年 月 日 */}
            {active == 1 ? (
              <View className='section'>
                <Picker
                  mode='date'
                  value='{day_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  onChange={this.bindDayDateChange.bind(this)}
                >
                  {date_right}
                </Picker>
              </View>
            ) : (
              <View />
            )}
            {/* 年 月 */}
            {active == 2 ? (
              <View className='section'>

                <Picker
                  mode='date'
                  value='{month_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  fields='month'
                  onChange={this.bindMonthDateChange.bind(this)}
                >
                  {date_right}
                </Picker>
              </View>
            ) : (
              <View />
            )}
            {/* 自定义 不显示右侧 picker  */}
            {active == 3 ? (
              <View />
            ) : (
              <Image
                className='arrow-right-image-rotate'
                src='https://resource.ivcheng.com/resources/images/arrow-right.png'
              />
            )}
          </View>
        </View>
        {/* 自定义 日期区间选择器 */}
        {!show ? (
          <View />
        ) : (
          <View className='select-time-start-end'>
            <View className='item'>
              <Picker
                mode='date'
                value='{start_date}'
                start='1970-01-01'
                end='2050-01-01'
                onChange={this.bindStartDateChange.bind(this)}
              >
                <View className='pickerr'>{start_date}</View>
              </Picker>
            </View>
            <View style='color: #666;'>—</View>
            <View className='item'>
              <Picker
                mode='date'
                value='{end_date}'
                start='1970-01-01'
                end='2050-01-01'
                onChange={this.bindEndDateChange.bind(this)}
              >
                <View className='pickerr'>{end_date}</View>
              </Picker>
            </View>
          </View>
        )}
        {/*  onClick={this.jump.bind(this, 0)} */}
        {/* 中间 数据总览 */}
        <View className='top-data'>
          <View className='list-top-one'>
            <View className='list-top-one-money'>{userIdentity.allBalance || 0}</View>
            <View className='list-top-one-title'>收益(元)
              <View onClick={this.showTips.bind(this, 1)} className='aticon'>
                <AtIcon value='help' size='14' color='#999' />
              </View>
            </View>
            {tipsNum == 1 && <Block>
              <View className='tips twos'>收益 = 商品佣金 + 邀请奖励</View>
              <View className='overlay' onClick={()=> { this.setState({ tipsNum: 0 }) }} />
            </Block> }
            <View className='list-top-one-sub-title'>含待结算:{userIdentity.unWithdrawBalance || 0}元</View>
          </View>
          <View className='line-through' />
          <View className='list-top-else-wrapper'>
            <View onClick={this.jumpOther.bind(this, '/main/order/promotionOrder', 'promote')} className='list-top-else list-top-else-left'>
              <View className='list-top-one-money'>{infoOne.money}</View>
            <View className='list-top-one-title'>商品佣金(元)</View>
            <View className='list-top-one-sub-title'>含待结算:{infoOne.earningsMoney}元</View>
            </View>
            <View onClick={this.jumpOther.bind(this, '/main/order/promotionOrder', 'invite')} className='list-top-else'>
              <View className='list-top-one-money'>{infoTwo.money}</View>
            <View className='list-top-one-title'>邀请奖励(元)</View>
            <View className='list-top-one-sub-title'>含待结算:{infoTwo.earningsMoney}元</View>
            </View>
          </View>
        </View>
        <View className='top-data top-data-center'>
          <View className='list-top-else-wrapper'>
            <View onClick={this.jumpOthers.bind(this, '/main/order/promotionOrder')} className='list-top-else list-top-else-left'>
              <View className='list-top-one-money'>{childData.total_fee}</View>
              <View className='list-top-one-title'>累计销售额(元)</View>
            </View>
            <View onClick={this.jumpOthers.bind(this, '/main/order/promotionOrder')} className='list-top-else'>
              <View className='list-top-one-money'>{childData.order_number}</View>
              <View className='list-top-one-title'>累计订单(笔)</View>
            </View>
          </View>
          <View className='line-through' />
          <View className='list-top-else-wrapper'>
            <View onClick={this.jumpOthers.bind(this, '/other/my/customer', '')} className='list-top-else list-top-else-left'>
              <View className='list-top-one-money'>{childData.customer_num}</View>
              <View className='list-top-one-title'>累计用户(人)</View>
            </View>
            <View onClick={this.jumpOthers.bind(this, '/other/my/myInvite', '')} className='list-top-else'>
              <View className='list-top-one-money'>{childData.child_seller_num}</View>
              <View className='list-top-one-title'>累计邀请(人)</View>
            </View>
          </View>
        </View>
        {/* 收益榜TOP3 */}
        {listTableData.length !== 0 &&
        <View className='top-three'>
          <View className='title-box'>
            <View className='big-title'>收益榜TOP3</View>
            <View className='tip'>小贴士：建议您多推广以下商品哦</View>
          </View>
          <View className='list-two'>
            {listTableData &&
            listTableData.map(item => (
              <View key={item.id} onClick={this.onNavigateTo.bind(this, item.navigateto, item.onSale)}
                className='list-two-item flex-row'
              >
                <View className='img-box'>
                  <Image src={item.url} mode='aspectFill' className='img' />
                </View>
                {item.onSale ? (
                  <View className='else'>
                    <View className='title'>{item.title}</View>
                    <View className='under-title-hang flex-row mar-top-10'>
                      <View className='under-title flex-row'>
                        <View>预估收益</View>
                        <View className='price-style mar-lef-5'>￥{item.get}</View>
                      </View>
                      <View className='dark-line' />
                      <View className='under-title under-title-two flex-row'>
                        <View>订单量</View>
                        <View className='mar-lef-5'>{item.orderNums}</View>
                      </View>
                    </View>
                  </View>
                ) : (
                  <View className='else yixiajia'>
                    <View className='yixiajia-hang title'>
                      <Text className='yixiajia-tag'>已下架</Text>
                      <Text>{item.title}</Text>
                    </View>
                    <View className='under-title-hang flex-row mar-top-10 color-989898'>
                      <View className='under-title flex-row'>
                        <View className='color-989898'>预估收益</View>
                        <View className='price-style color-989898 mar-lef-5'>
                          ￥{item.get}
                        </View>
                      </View>
                      <View className='dark-line' />
                      <View className='under-title under-title-two flex-row'>
                        <View className='color-989898'>订单量</View>
                        <View className='color-989898 mar-lef-5'>{item.orderNums}</View>
                      </View>
                    </View>
                  </View>
                )}
              </View>
            ))}
          </View>
        </View>
        }
      </View>
    );
  }
}
